<?php

/*
 * This file is part of PHP CS Fixer.
 *
 * (c) wangyt <wangtom365@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace App\Http\Controllers\Admins;

use App\Models\CategoryModel;
use App\Models\ModuleModel;
// use Symfony\Component\Yaml\Yaml;
// use Symfony\Component\Yaml\Exception\ParseException;
use App\Models\Post\PostModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CategoryController extends AdminController
{
    /**
     * 列表.
     *
     * @param mixed $module
     *
     * @return string
     */
    public function index(Request $request, $module = '')
    {
        return $this->showList($request, $module);
    }

    /**
     * @param Request $request
     * @param string  $module
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function showList(Request $request, $module = '')
    {
        $page = $request->input('page', 0);
        $data = [];

        $data['moduleList'] = (new ModuleModel())->getListData(collect([
            'where' => [
                'module_status' => 1,
            ],
        ]));

        $conditions = collect();
        if ($module) {
            $conditions['where'] = ['module' => $module];
        }

        $data['module'] = $module;
        $data['categoryList'] = (new CategoryModel())->getListData($conditions, false);
        // $data['categoryCount'] = (new PostModel())->getListGroupByCategory();
        $categoryMenu = collect($data['categoryList'])->where('parent_id', 0)->groupBy('platform');

        // $data['categoryMenu'] = $categoryMenu->toArray();

        return view('admins.categories.list', $data);
    }

    public function add(Request $request)
    {
        // print_r($request->all());

        if ($request->input('_submit') !== null) {
            $response = [
                'code' => 0,
                'msg' => '',
                'data' => [],
                'time' => time(),
            ];
            $input = [];
            $input['platform'] = $request->input('platform', 'cms');
            $input['module'] = $request->input('module', '');
            $input['parent_id'] = $request->input('parent_id', 0);
            $input['category_name'] = $request->input('category_name', '');
            $input['category_name_en'] = $request->input('category_name_en', '');
            if ($request->input('remark', '')) {
                $input['remark'] = $request->input('remark', '');
            }
            $input['created_at'] = date('Y-m-d H:i:s');
            // $input['updated_at']  = date('Y-m-d H:i:s');

            $result = (new CategoryModel())->saveData(collect($input));

            if ($result) {
                $response['code'] = 1;
                $response['data'] = $result;
            }
        // print_r($input);
            return response($response, 200);
        }
        $data['categoryList'] = (new CategoryModel())->getList();
        $data['parentCategoryList'] = (new CategoryModel())->getParentCategoryList();
                // print_r($data['parentCategoryList']);exit;
        $data['configs'] = $this->getYamlContent(config_path('admins/category.yaml'));
        // print_r($data);exit;

//        $data['formOptions']['module'] = collect($this->getModuleList())->mapWithKeys(function($item){
//            return [$item['module_name_en'] => $item['module_name']];
//        });
//        // print_r($data);exit;
//        $data['formOptions']['parent_id'] = collect($data['parentCategoryList'])->mapWithKeys(function($item){
//            // print_r($item);
//            return [$item['category_id'] => $item['category_name']];
//        });
        $data['formValueList'] = [
            'module' => $request->input('module', ''),
            'parent_id' => $request->input('parent_id', ''),
        ];
        $data['formOptionList'] = [
            'module' => collect($this->getModuleList())->mapWithKeys(function ($item) {
                return [$item['module_name_en'] => $item['module_name']];
            })->toArray(),
            'parent_id' => collect($data['parentCategoryList'])->mapWithKeys(function ($item) {
                // print_r($item);
                return [$item['category_id'] => $item['category_name']];
            })->toArray(),
        ];
        // print_r($data);exit;

        // print_r($data['options']);exit;

        return view('admins.categories.add', $data);
    }

    public function edit(Request $request, $id = 0)
    {
        // try {
//     $content = Yaml::parse(file_get_contents(config_path('admins/category.yaml')));
//     print_r($content);
// } catch (ParseException $e) {
//     printf("Unable to parse the YAML string: %s", $e->getMessage());
// }

        if ($request->input('_submit') !== null) {
            $response = [
                'code' => 0,
                'msg' => '',
                'data' => [],
                'time' => time(),
            ];
            $input = [];
            $input['platform'] = $request->input('platform', 'cms');
            $input['module'] = $request->input('module', '');
            $input['parent_id'] = $request->input('parent_id', 0);
            $input['category_name'] = $request->input('category_name', '');
            $input['category_name_en'] = $request->input('category_name_en', '');
            if ($request->input('remark', '')) {
                $input['remark'] = $request->input('remark', '');
            }
            $input['updated_at'] = date('Y-m-d H:i:s');

            $where = [
                'category_id' => $id,
            ];
            $result = DB::table('ks_categories')
                ->where($where)
                ->update($input);
            if ($result) {
                $response['code'] = 1;
            }
        // print_r($input);
            return response($response, 200);
        }

        $result = (new CategoryModel())->find($id);
        if (empty($result)) {
            return '没有获取到数据.请确认URL是否正确.';
        }

        $result = $result->toArray();
        $data['detail'] = $result;
        $data['parentCategoryList'] = (new CategoryModel())->getParentCategoryList();

        $data['options'] = [];
        $data['configs'] = $this->getYamlContent(config_path('admins/category.yaml'));
        // print_r($data);exit;

        $data['options']['module'] = collect($this->getModuleList())->mapWithKeys(function ($item) {
            return [$item['module_name_en'] => $item['module_name']];
        });

        $data['options']['parent_id'] = collect($data['parentCategoryList'])->mapWithKeys(function ($item) {
            // print_r($item);
            return [$item['category_id'] => $item['category_name']];
        });

        $data['formValueList'] = $result;
        // print_r($data);exit;
        $data['formOptionList'] = [
            'module' => collect($this->getModuleList())->mapWithKeys(function($item){
                return [$item['module_name_en'] => $item['module_name']];
            })->toArray(),
            'parent_id' => collect($data['parentCategoryList'])->mapWithKeys(function($item){
                // print_r($item);
                return [$item['category_id'] => $item['category_name']];
            })->toArray(),
        ];

        return view('admins.categories.edit', $data);
    }
}
